import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from '@/views/main/Main.vue'
import Home from '@/views/home/Home.vue'
import Mine from '@/views/mine/Mine.vue'
import Login from '@/views/login/Login.vue'
import Search from '@/views/search/Search.vue'
import SearchResult from '@/views/searchResult/SearchResult.vue'
// 导入文章详情组件
import ArticleDetail from '@/views/articleDetail/ArticleDetail.vue'
import UserEdit from '@/views/userEdit/UserEdit.vue'
import store from '@/store/index.js'

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(() => {})
}

Vue.use(VueRouter)
const routes = [
  // 登录组件的路由规则（带有 name 属性的路由规则，叫做“命名路由”）
  { path: '/login', component: Login, name: 'login' },
  {
    path: '/',
    component: Main,
    children: [
      // path 为"空字符串"的子路由规则，叫做"默认子路由"
      {
        path: '',
        component: Home,
        name: 'home',
        meta: { isRecord: true, top: 0 }
      },
      // 我的子路由规则
      { path: '/mine', component: Mine, name: 'mine' }
    ]
  },
  { path: '/search', component: Search },
  // name: 'search-result'
  { path: '/search/:kw', component: SearchResult, props: true },
  // 文章详情的路由规则
  {
    path: '/article/:id',
    component: ArticleDetail,
    name: 'art-detail',
    props: true,
    meta: { isRecord: true, top: 0 }
  },
  { path: '/user/edit', component: UserEdit, name: 'user-edit' }
]

const router = new VueRouter({
  routes
})

const pathArr = ['/mine', '/user/edit']
router.beforeEach((to, from, next) => {
  if (pathArr.indexOf(to.path) !== -1) {
    const tokenStr = store.state.tokenInfo.token
    if (tokenStr) {
      // 1.1 token 有值，已登录过（操作：直接放行）
      next()
    } else {
      // 1.2 token 不存在，没有登录（操作：强制跳转到登录页）
      // next('/login')
      // now：没有登录，强制跳转到登录页，并携带路由的 "query 查询参数"
      // router.push(`/login?pre=${to.fullPath}`)
      // next('/login')
      next('/login?pre=' + to.fullPath)
    }
  } else {
    next()
  }
})

// 全局后置钩子
router.afterEach((to, from) => {
  // 如果当前的路由的元信息中，isRecord 的值为 true
  if (to.meta.isRecord) {
    setTimeout(() => {
      // 则把元信息中的 top 值设为滚动条纵向滚动的位置
      window.scrollTo(0, to.meta.top)
    }, 0)
  }
})

export default router
